package com.htpay.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.htpay.model.eo.AlipayAccount;
import com.htpay.model.vo.AlipayResponseModel;
import com.htpay.util.common.JsonConvertUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class AlipayApiUtil {

    /**
     * 创建预收款二维码
     *
     * @param appId
     * @param appKey
     * @param publicKey
     * @param tradeNo
     * @param money
     * @param subject
     * @return
     * @throws AlipayApiException
     */
    public static AlipayResponseModel createAlipayPreTradeReq(AlipayAccount aact, String tradeNo, double money, String subject, String notifyUrl) {
        try {
            //获取当前应用的配置信息
            String appId = aact.getAppId();
            String appKey = aact.getAppKey();
            String publicKey = aact.getAppPublicKey();

            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, appKey, "json", "GBK", publicKey, "RSA2");
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            //设置回调通知接口
            request.setNotifyUrl(notifyUrl);
            request.setBizContent("{" +
                    "\"out_trade_no\":" + tradeNo + "," +
                    "\"total_amount\":" + money + "," +
                    "\"subject\":\"" + subject + "\"," +
                    "\"timeout_express\":\"15m\"," +
                    "\"qr_code_timeout_express\":\"10m\"" +
                    "  }");

            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            //打印生成预付款二维码信息
            System.out.println(JsonConvertUtil.objectToJson(response));
            AlipayResponseModel model = new AlipayResponseModel();
            model.setCode(response.getCode());
            model.setMsg(response.getMsg());

            if (response.isSuccess()) {
                System.out.println("==== 调用支付宝预收款通道成功: code[" + response.getCode() + "] ," + response.getMsg() + " ====");
                model.setOutTradeNo(response.getOutTradeNo());
                model.setQrCode(response.getQrCode());
                model.setIsSuccess(true);
            } else {
                System.out.println("==== 调用支付宝预收款通道失败: code[" + response.getCode() + "] ," + response.getMsg() + " ====");
                System.out.println("==== 返回业务错误码信息: sub_code[" + response.getSubCode() + "] ," + response.getSubMsg() + " ====");
                model.setIsSuccess(false);
            }

            return model;
        } catch (AlipayApiException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
}
